package com.yjs.ppjokedemo.repo;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.yjs.ppjokedemo.bean.VideoEntity;
import com.yjs.ppjokedemo.bean.VideoProduct;
import com.yjs.ppjokedemo.request.Request;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 视频的数据库 负责网络请求 M层的功能
 *
 * */
public class VideoRepo {

    //使用的数据源
    private MutableLiveData<List<VideoProduct>> mutableProductList;

    //问题3 起初并未同步
    public synchronized LiveData<List<VideoProduct>> getProducts(){
        if (mutableProductList == null){
            mutableProductList = new MutableLiveData<>();
            loadProducts();
        }
        return mutableProductList;
    }

    private void loadProducts() {
        //创建需要给LiveData的集合
        List<VideoProduct> productList = new ArrayList<>();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Request.HOST)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Call<VideoEntity> call = retrofit.create(Request.class).getBean();
        call.enqueue(new Callback<VideoEntity>() {
            @Override
            public void onResponse(Call<VideoEntity> call, Response<VideoEntity> response) {
                //解析数据
                for (int i=0; i<response.body().data.size(); i++){
                    VideoProduct videoProduct = new VideoProduct(
                            response.body().data.get(i).getAuthname(),
                            response.body().data.get(i).getCaption(),
                            response.body().data.get(i).getVideopath(),
                            response.body().data.get(i).getVideomainimg()

                    );
                    productList.add(videoProduct);
                }
                Log.i("TagA", "onResponse: ");
                mutableProductList.setValue(productList);
            }

            @Override
            public void onFailure(Call<VideoEntity> call, Throwable t) {
                Log.i("TagA","e:"+ t.getMessage());
            }
        });
    }
}
